﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectCloth.Entity;

namespace ProjectCloth.FrmUI
{
    public partial class SimpleStatsFrm : UserControl
    {
        private ClothContext db = new ClothContext();
        List<Product> productList = new List<Product>();
        List<Product> products = new List<Product>();
        private int _period = 7;
        bool A, B, C, D, E, ALL = false;
        public SimpleStatsFrm()
        {
            InitializeComponent();
            productList = db.Products.ToList();
            CheckChange(null, null);
        }
        private void CheckChange(object sender, EventArgs e)
        {
            A = checkA.Checked;
            B = checkB.Checked;
            C = checkC.Checked;
            D = checkD.Checked;
            E = checkE.Checked;
            ALL = checkAll.Checked;
            products = productList.Where(o =>
            (A && o.ProductLevel == "A")
            || (B && o.ProductLevel == "B")
            || (C && o.ProductLevel == "C")
            || (D && o.ProductLevel == "D")
            || (E && o.ProductLevel == "E")
            || (ALL)).ToList();
            //searchBtn_Click(null, null);
        }

        private void searchBtn_Click(object sender, EventArgs e)
        {
            var endDay = endDatePicker.Value.Date;
            var startDate = endDay.AddDays(-12 * _period);
            var colorQuantiyList = (from a in db.ColorCards.Where(o => o.MakeTime >= startDate && o.MakeTime < endDay && o.Enabled)
                                    group a by a.ColorCardNo into b
                                    select new
                                    {
                                        ProductNo = b.Key,
                                        Quantity = b.Sum(o => o.Quantity),
                                    }).ToList();

            var BatchQuantityList = (from a in db.SaleOrderItems.Where(o => o.InMoneyDate >= startDate && o.InMoneyDate < endDay && o.OrderNo.StartsWith("D"))
                                     group a by a.ProductId into b
                                     select new
                                     {
                                         ProductId = b.Key,
                                         Quantity = b.Sum(o => o.Quantity),
                                     }).ToList();
            var simpleQuantityList = (from a in db.SaleOrderItems.Where(o => o.CreateDate >= startDate && o.CreateDate < endDay && o.OrderNo.StartsWith("J"))
                                      group a by a.ProductId into b
                                      select new
                                      {
                                          ProductId = b.Key,
                                          Quantity = b.Sum(o => o.Quantity),
                                      }).ToList();
            var simpleFreList = (from a in db.SaleOrderItems.Where(o => o.InMoneyDate >= startDate && o.InMoneyDate < endDay && o.OrderNo.StartsWith("J"))
                                     //group a by a.ProductId into b
                                 select new OrderProduct()
                                 {
                                     OrderId = a.OrderId,
                                     ProductId = a.ProductId
                                 }).ToList();
            //var saleOrderItemList = db.SaleOrderItems.Where(o => o.CreateDate >= startDate && o.CreateDate < endDay && o.OrderNo.StartsWith("D")).ToList();
            var saleOrderItemList = (from a in db.SaleOrderItems.Where(o => o.OrderNo.StartsWith("J") && o.InMoneyDate < endDay && o.InMoneyDate >= startDate)
                                     select new SaleOrderItemLight
                                     {
                                         CreateDate = a.InMoneyDate,
                                         OrderId = a.OrderId,
                                         ProductId = a.ProductId,
                                         Quantity = a.Quantity
                                     }).ToList();
            //var saleOrderItemList = db.SaleOrderItems.SqlQuery($"SELECT OrderId,CreateDate,ProductId,Quantity from  saleorderitem where OrderNo like 'J%' AND CreateDate>='{startDate.ToString()}' and  CreateDate>='{endDay.ToString()}'").ToList();
            List<ProductSimpleStats> simpleStats = new List<ProductSimpleStats>();
            foreach (var p in products)
            {
                simpleStats.Add(new ProductSimpleStats
                {
                    ProductId = p.Id,
                    ProductNo = p.ProductNo,
                    ProductLevel = p.ProductLevel,
                    ColorTypeQuantity =GetIntNullable((int) colorQuantiyList.Where(o => o.ProductNo == p.ProductNo).Select(o => o.Quantity).FirstOrDefault()),
                    BatchQuantity =GetIntNullable((int)BatchQuantityList.Where(o => o.ProductId == p.Id).Select(o => o.Quantity).FirstOrDefault()),
                    SimpleQuantity =GetIntNullable((int)simpleQuantityList.Where(o => o.ProductId == p.Id).Select(o => o.Quantity).FirstOrDefault()),
                    SimpleFrequency = GetIntNullable(simpleFreList.Where(o => o.ProductId == p.Id).DistinctBy(o => o.OrderId).Count()),
                    PeriodQuantity_1 =GetIntNullable(GetPeriodQuantity(saleOrderItemList, p.Id, endDay, 1)),
                    PeriodQuantity_2 =GetIntNullable(GetPeriodQuantity(saleOrderItemList, p.Id, endDay, 2)),
                    PeriodQuantity_3 =GetIntNullable(GetPeriodQuantity(saleOrderItemList, p.Id, endDay, 3)),
                    PeriodQuantity_4 =GetIntNullable(GetPeriodQuantity(saleOrderItemList, p.Id, endDay, 4)),
                    PeriodQuantity_5 =GetIntNullable(GetPeriodQuantity(saleOrderItemList, p.Id, endDay, 5)),
                    PeriodQuantity_6 =GetIntNullable(GetPeriodQuantity(saleOrderItemList, p.Id, endDay, 6)),
                    PeriodQuantity_7 =GetIntNullable(GetPeriodQuantity(saleOrderItemList, p.Id, endDay, 7)),
                    PeriodQuantity_8 =GetIntNullable(GetPeriodQuantity(saleOrderItemList, p.Id, endDay, 8)),
                    PeriodQuantity_9 =GetIntNullable(GetPeriodQuantity(saleOrderItemList, p.Id, endDay, 9)),
                    PeriodQuantity_10 =GetIntNullable(GetPeriodQuantity(saleOrderItemList, p.Id, endDay, 10)),
                    PeriodQuantity_11 =GetIntNullable(GetPeriodQuantity(saleOrderItemList, p.Id, endDay, 11)),
                    PeriodQuantity_12 =GetIntNullable(GetPeriodQuantity(saleOrderItemList, p.Id, endDay, 12)),

                });
            }
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = new SortableBindingList<ProductSimpleStats>(simpleStats.OrderByDescending(o=>o.SimpleQuantity).ToList());

        }
        private int GetPeriodQuantity(List<SaleOrderItemLight> saleOrderItem, int comparaKey, DateTime endDate, int beforePeroid)
        {
            int period = _period;
            //if (onSaleProducts == null || onSaleProducts.Count <= 0) return 0;
            var end = endDate.Date;
            var start = end.AddDays(-beforePeroid * period);
            return saleOrderItem.Where(o => o.CreateDate >= start && o.CreateDate <= start.AddDays(period)).DistinctBy(o => o.OrderId).Count(o => o.ProductId == comparaKey);
        }
        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //自动编号，与数据无关
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
               e.RowBounds.Location.Y,
               dataGridView1.RowHeadersWidth - 4,
               e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,
                  (e.RowIndex + 1).ToString(),
                   dataGridView1.RowHeadersDefaultCellStyle.Font,
                   rectangle,
                   dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                   TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }
        private void periodUpDown_ValueChanged(object sender, EventArgs e)
        {
            _period = (int)periodUpDown.Value;
        }
        private string GetNumString(decimal quantity)
        {
            return quantity > 0 ? ((int)quantity).ToString() : "";
        }
        private string GetNumString(int quantity)
        {
            return quantity > 0 ? quantity.ToString() : "";
        }
        private int? GetIntNullable(int quantity)
        {
            return quantity > 0 ? quantity : (int?)null;
        }
        internal class SaleOrderItemLight
        {
            public DateTime CreateDate { get; set; }
            public int OrderId { get; set; }
            public int ProductId { get; set; }
            public decimal Quantity { get; set; }
        }

        private void btnExport_Click(object sender, EventArgs e) => Helper.ExportDgv(dataGridView1, "剪版频率统计");

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }
    }
}
